import axios from 'axios'
import Cookies from 'js-cookie'
import errorFun from './error'

const timeout = 20000

const instance = axios.create({
  baseURL: ``,
  timeout, // 设置20s超时
})

// 设置请求拦截器
instance.interceptors.request.use(
  (config) => {
    // get/delete/head/options请求通过query形式(params) 传参，post/put/patch请求通过request body形式(data)传参
    const method = config.method
    let type = 'data'
    if (['get', 'delete', 'head', 'options'].includes(method)) {
      type = 'params'
    } else {
      // 判断是否是responseType的传参
      const { params, ...info } = config[type]
      config = { ...config, ...info }
      config[type] = params
    }
    if (!config[type]) {
      config[type] = {}
    }
    // 设置token
    config.headers = {
      Authorization: Cookies.get(process.env.envConfig.TOKEN),
    }
    return config
  },
  () => {
    return Promise.reject({
      message: '当前网络不佳，请稍后再试-1',
    })
  }
)

// 设置响应拦截器
instance.interceptors.response.use(
  (res) => {
    // 流文件直接返回
    if (res.config.responseType == 'blob') {
      return res
    }
    const { status } = res || {}
    const { data, msg, code } = res?.data || {}
    if (!status) {
      return Promise.reject({
        data: res.data,
        message: msg || '当前网络不佳，请稍后再试-2',
      })
    } else if (Number(code) !== 200) {
      errorFun(code)
      ElMessage({ message: msg, type: 'error', duration: 1000 })
      return Promise.reject({
        data: res.data,
        message: msg || '当前网络不佳，请稍后再试-3',
      })
    }
    return data
  },
  (err) => {
    // 处理接口请求超时
    if (err.message === `timeout of ${timeout}ms exceeded`) {
      return Promise.reject({
        message: `接口请求失败: 超过${timeout / 1000}秒无响应`,
      })
    }

    return Promise.reject(err.response.data)
  }
)

export default instance
